package com.exampleyyy.demoyyy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exampleyyy.demoyyy.ServiceJieKou.OrderServiceJieKou;
import com.exampleyyy.demoyyy.ShiTi.*;
import com.exampleyyy.demoyyy.ShiTiJieKou.OrderMapper;
import com.exampleyyy.demoyyy.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderService extends ServiceImpl<OrderMapper, Orders> implements OrderServiceJieKou {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 提交订单的业务逻辑实现
     *
     * 本方法通过将购物车中的商品添加到订单中，完成订单的提交
     * 它首先从当前用户获取购物车中的所有商品，计算总价，并生成订单详情
     * 然后，它会检查收货地址的有效性，并生成唯一的订单号
     * 最后，它将订单和订单详情保存到数据库，并清空购物车
     */
    @Transactional
    public Integer submit(Orders orders) {
        try {
            // 获取当前用户ID
            Long userId = BaseContext.getCurrentId();

            // 构建查询条件，用于查询当前用户的购物车商品
            LambdaQueryWrapper<ShoppingCart> Wrapper = new LambdaQueryWrapper<>();
            Wrapper.eq(ShoppingCart::getUserId, userId);

            // 从购物车服务中查询商品列表
            List<ShoppingCart> shoppingCarts = shoppingCartService.list(Wrapper);

            // 检查购物车是否为空
            if (shoppingCarts == null || shoppingCarts.size() == 0) {
                throw new ClassCastException("购物车为空，不能下单");
            }

            // 获取当前用户信息
            User user = userService.getById(userId);
            // 获取订单收货地址ID，并查询收货地址信息
            Long addressBookId = orders.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);
            // 检查收货地址是否有效
            if (addressBook == null) {
                throw new ClassCastException("地址有误，不能下单");
            }

            // 生成订单号
            long orderId = IdWorker.getId();//订单号

            // 使用AtomicInteger来累计订单总金额，避免并发问题
            AtomicInteger amount = new AtomicInteger(0);
            // 根据购物车商品生成订单详情列表
            List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(orderId);
                orderDetail.setNumber(item.getNumber());
                orderDetail.setDishFlavor(item.getDishFlavor());
                orderDetail.setDishId(item.getDishId());
                orderDetail.setSetmealId(item.getSetmealId());
                orderDetail.setName(item.getName());
                orderDetail.setImage(item.getImage());
                orderDetail.setAmount(item.getAmount());
                // 累加商品金额到订单总金额
                amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

                return orderDetail;
            }).collect(Collectors.toList());

            // 设置订单基本信息
            orders.setId(orderId);
            orders.setOrderTime(LocalDateTime.now());
            orders.setCheckoutTime(LocalDateTime.now());
            orders.setStatus(2);// 设置订单状态，2表示已提交
            orders.setAmount(new BigDecimal(amount.get()));// 设置订单总金额
            orders.setUserId(userId);
            orders.setNumber(String.valueOf(orderId));
            orders.setUserName(user.getName());
            orders.setConsignee(addressBook.getConsignee());
            orders.setPhone(addressBook.getPhone());
            orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                    + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                    + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                    + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
            // 保存订单信息
            this.save(orders);
            // 批量保存订单详情
            orderDetailService.saveBatch(orderDetails);
            // 清空当前用户的购物车
            shoppingCartService.remove(Wrapper);
            return 1;
        } catch (Exception e) {
            log.error("下单失败：{}", e.getMessage());
            return 0;
        }
    }
}